package com.codez.unionpay.netty;

import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *  @author codez
 *	@createTime 2019-05-18 04:39:15
 */

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
	
	Logger logger = LoggerFactory.getLogger(NettyServer.class);
	
	/**
	 * 连接创建的时候
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info(" 当前有新用户连接 " + ctx.channel());
	}
	
	/**
	 * 读数据的时候创建
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf) msg;
		Scanner scanner = new Scanner(System.in);
//		logger.info(" from client >  " + in.toString(Charsets.UTF_8));
		System.out.println(" from client > " + in.toString(Charsets.UTF_8));
		if(in.toString(Charsets.UTF_8) .contains("exit")){
			logger.info(" 关闭客户端连接 ");
			ctx.close();
		}
//		logger.info(" response client > ");
		System.out.print(" response server > ");
		ctx.channel().writeAndFlush(Unpooled.copiedBuffer(scanner.nextLine() , Charsets.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		ctx.close();
	}
	
}
